package utils

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
)

const (
	SuccessCode    int    = 0
	ErrorCode      int    = -1
	SuccessMessage string = "success"
)

type response struct {
	// 代码
	Code int `json:"code" example:"200"`
	// 数据集
	Data interface{} `json:"data"`
	// 消息
	Message string `json:"message"`
}

var Response = new(response)

func (*response) Json(r *ghttp.Request, code int, msg string, data ...interface{}) *response {
	responseData := interface{}(nil)
	if len(data) > 0 {
		responseData = data[0]
	}
	response := &response{
		Code:    code,
		Message: msg,
		Data:    responseData,
	}
	r.SetParam("apiReturnRes", response)
	err := r.Response.WriteJson(response)
	if err != nil {
		g.Log("响应写入json错误").Error(err)
		panic(err)
	}

	return response
}

func (*response) SuccessResponse(r *ghttp.Request) {
	_ = Response.Json(r, SuccessCode, "success")

}

func (*response) ErrorResponse(isExit bool, r *ghttp.Request, msg string) {
	_ = Response.Json(r, ErrorCode, msg)

	if isExit {
		r.Exit()
	}
}

func (*response) ErrorResponseExit(r *ghttp.Request, message string) {
	Response.ErrorResponse(true, r, message)
}
func (*response) ErrorResponseExitOnError(r *ghttp.Request, err error) {
	if err != nil {
		Response.ErrorResponse(true, r, err.Error())
	}
	Response.ErrorResponse(true, r, "未知错误")
}

func (*response) JsonRedirect(r *ghttp.Request, code int, message, redirect string, data ...interface{}) {
	responseData := interface{}(nil)
	if len(data) > 0 {
		responseData = data[0]
	}
	r.Response.WriteJson(response{
		Code:    code,
		Message: message,
		Data:    responseData,
	})
}
func (*response) JsonRedirectExit(r *ghttp.Request, code int, message, redirect string, data ...interface{}) {
	Response.JsonRedirect(r, code, message, redirect, data...)
	r.Exit()
}
